package com.betterman.controller;


import com.betterman.pojo.User;
import com.betterman.pojo.bo.ModifiedUserBO;
import com.betterman.pojo.bo.RegisterUserBO;
import com.betterman.pojo.vo.UserVO;
import com.betterman.service.UserService;
import com.betterman.utils.JSONResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author fox
 * @since 2020-08-05
 */
@Api(value="用户相关", tags={"用户相关接口"})
@RestController
@RequestMapping("/user")
public class UserController extends BaseController {

    /**
     * 用户服务
     */
    @Autowired
    private UserService userService;

    /**
     * 用户退出登录<br>
     * token 存放在 redis 中，登陆产生随机值保存到 redis 中。
     *
     * @param userId userId
     * @return JSONResult json 返回结果
     * @author <a href="mailto:foxfocus@163.com">fox</a>
     */
    @ApiOperation(value="用户退出登录", notes="执行用户退出登录的操作接口", httpMethod = "POST")
    @ApiImplicitParams({@ApiImplicitParam(name = "userId", value = "用户主键id", required = true, dataType = "string", paramType = "query")})
    @PostMapping("/logout")
    public JSONResult logout(@RequestParam("userId") String userId){
        if (StringUtils.isBlank(userId)) {
           return JSONResult.errorMsg("参数不能为空");
        }

        // 登出就是清除会话，断开前后端的联系
        redisOperator.del(REDIS_UNIQUE_TOKEN + ":" + userId);
        return JSONResult.ok();
    }

    /**
     * 用户登录
     *
     * @param registerUserBO 用户登录对象
     * @return JSONResult json 返回结果
     * @author <a href="mailto:foxfocus@163.com">fox</a>
     */
    @ApiOperation(value="用户登录", notes="用户登录入口", httpMethod = "POST")
    @ApiImplicitParams({@ApiImplicitParam(name = "registUserBO", value = "用户对象", required = true, dataType = "RegistUserBO", paramType = "body")})
    @PostMapping("/login")
    public JSONResult login(@RequestBody RegisterUserBO registerUserBO) {
        if (StringUtils.isAnyBlank(registerUserBO.getPassword(), registerUserBO.getUsername())) {
           return JSONResult.errorMsg("用户信息均不能为空");
        }
        User user = userService.loginRegister(registerUserBO);
        return JSONResult.ok(setToken(user));
    }


    /**
     * 用户注册
     *
     * @param registerUserBO 用户登录对象
     * @return JSONResult json 返回结果
     * @author <a href="mailto:foxfocus@163.com">fox</a>
     */
    @ApiOperation(value="用户注册", notes="用户注册的入口", httpMethod = "POST")
    @ApiImplicitParams({@ApiImplicitParam(name = "registUserBO", value = "用户对象", required = true, dataType = "RegistUserBO", paramType = "body")})
    @PostMapping("/register")
    public JSONResult register(@RequestBody RegisterUserBO registerUserBO) {
        if (StringUtils.isAnyBlank(registerUserBO.getPassword(), registerUserBO.getUsername())) {
            return JSONResult.errorMsg("用户信息均不能为空");
        }
        // 判断用户是否存在，不存在再保存注册信息
        boolean userIsExists = userService.queryUserIsExists(registerUserBO.getUsername());
        User user = userIsExists ? null : userService.saveRegisterUser(registerUserBO);
        return JSONResult.ok(setToken(user));
    }

    /**
     * 修改昵称
     *
     * @param userBO 修改用户对象
     * @return JSONResult json 返回结果
     * @author <a href="mailto:foxfocus@163.com">fox</a>
     */
    @ApiOperation(value="修改昵称", notes="用户修改账号昵称的接口", httpMethod = "POST")
    @ApiImplicitParams({@ApiImplicitParam(name = "userBO", value = "用户修改对象", required = true, dataType = "ModifiedUserBO", paramType = "body")})
    @PostMapping("/modifyUserinfo")
    public JSONResult modifyUserinfo(@RequestBody ModifiedUserBO userBO){

        String userId = userBO.getUserId();
        if (StringUtils.isBlank(userId)) {
            return JSONResult.errorMsg("用户id不能为空");
        }

        // 以下三个属性必须至少有一项是不为空的
//        String birthday = userBO.getBirthday();
        Integer sex = userBO.getSex();
//        String nickname = userBO.getNickname();
//        if (StringUtils.isBlank(birthday) && StringUtils.isBlank(nickname) && sex == null) {
//            return JSONResult.errorMsg("修改用户信息不能为空");
//        }

        if (sex != null && sex != 0 && sex != 1) {
            return JSONResult.errorMsg("性别不正确 - [1:男][0:女]");
        }

//        if (StringUtils.isNotBlank(nickname) && nickname.length() > 12) {
//            return JSONResult.errorMsg("昵称长度不能超过12位");
//        }

//        if (StringUtils.isNotBlank(birthday)) {
//            if (!DateUtil.isValidDate(birthday, DateUtil.ISO_EXPANDED_DATE_FORMAT)) {
//                return JSONResult.errorMsg("生日日期格式不正确");
//            }
//        }

        // 保存地址到数据库
        User user = new User();
        user.setId(userId);
        user.setGender(sex.toString());
//        user.setBirthday(birthday);
//        user = userService.updateUserInfo(user);
        user.setPassword(null);

        return JSONResult.ok(conventUsersVO(user));
    }

    private UserVO conventUsersVO(User user) {
        String token = redisOperator.get(REDIS_UNIQUE_TOKEN + ":" + user.getId());
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        userVO.setUserUniqueToken(token);
        return userVO;
    }
}
